﻿using DTOs;
using JWT;
using JWT.Algorithms;
using JWT.Exceptions;
using JWT.Serializers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace OA.WebAPI.App_Start
{
	public class JWTHelper
	{
        //HMACSHA256加密
        static IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
        //序列化和反序列(JSON和对象)
        static IJsonSerializer serializer = new JsonNetSerializer();
        //Base64编解码
        static IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
        //UTC时间获取
        static IDateTimeProvider provider = new UtcDateTimeProvider();
        const string secret = "www.aoxiang.com";//加密和解密的密钥，不要泄露
                                                // 生成JWT token 字符串
        public static string GetToken(UserInfoDto user)
        {
            //设置过期时间(可以不设置，下面表示签名后 20分钟过期)
            double exp = (DateTime.UtcNow.AddMinutes(20) - new DateTime(1970, 1, 1)).TotalSeconds;

            var payload = new Dictionary<string, object>
            {
                { "Id", user.Id },
                { "Name",user.Name },
                //{ "OrgId",user.OrgId },
                //{ "OrgName",user.OrgName },
                { "RolesId",user.RolesId },
                { "exp",exp}
            };

            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            var token = encoder.Encode(payload, secret);
            return token;
        }
        // 解密token
        public static UserInfoDto DecodeToken(string token)
        {
            try
            {
                // 用来验证jwt token的对象
                IJwtValidator validator = new JwtValidator(serializer,
    provider);
                //用于解析JWT的类
                IJwtDecoder decoder = new JwtDecoder(serializer, validator,
    urlEncoder, algorithm);
                var json = decoder.Decode(token, secret, true); // 解密
                                                                
                return serializer.Deserialize<UserInfoDto>(json);  // 反序列化成对象
            }
            catch (TokenExpiredException)
            {
                throw new Exception("登录已过期！"); 
            }
            catch (SignatureVerificationException)
            {
                //校验未通过自动进入这里
                throw new Exception("非法登录！");
            }
            catch (Exception)
            {
                //其它错误
                throw new Exception("验证失败");
            }
        }

    }
}